package com.tally.server.service;

import com.tally.server.domain.UserInfo;
import com.tally.server.domain.UserInfoExample;
import com.tally.server.dto.LoginUserDTO;
import com.tally.server.dto.UserDTO;
import com.tally.server.dto.UserInfoDTO;
import com.tally.server.mapper.UserInfoMapper;
import com.tally.server.utils.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(UserInfoDTO userInfoDTO) {
        UserInfo userInfo = CopyUtil.copy(userInfoDTO, UserInfo.class);

        UserInfoExample userInfoExample = new UserInfoExample();
        userInfoExample.createCriteria().andUserIdEqualTo(userInfo.getUserId());
        if(userInfoMapper.countByExample(userInfoExample) > 0){
            update(userInfo);
        }else{
            insert(userInfo);
        }
    }

    /**
     * 新增
     */
    private void insert(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    /**
     * 更新
     */
    private void update(UserInfo userInfo) {
        userInfoMapper.updateByPrimaryKey(userInfo);
    }

    public UserInfoDTO selectByUserId(Integer userId){
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        return CopyUtil.copy(userInfo,UserInfoDTO.class);
    }
}
